package tq.com.tqstudent.ui.activity.classes;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.listener.OnPageErrorListener;
import com.lib.common.base.BaseActivity;
import com.lib.common.utils.FileUtil;
import com.lib.common.utils.LogUtil;
import com.lib.common.utils.SPUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.download.DownloadListener;
import com.lzy.okserver.download.DownloadTask;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import tq.com.tqstudent.App;
import tq.com.tqstudent.Constants;
import tq.com.tqstudent.R;
import tq.com.tqstudent.bean.BaseBean;
import tq.com.tqstudent.bean.MalistBean;
import tq.com.tqstudent.net.ok.DialogCallback;

/**
 * @Author rames
 * @date 2019/3/12 12:15
 */
public class PdfViewActivity extends BaseActivity implements OnPageChangeListener, OnLoadCompleteListener, OnPageErrorListener {
    @BindView(R.id.pdfView)
    PDFView pdfView;
    @BindView(R.id.progress_layout)
    LinearLayout progressLayout;
    @BindView(R.id.progress_tv)
    TextView progressTV;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;
    private int index;
    private String title;
    private String pdfName;
    private DownloadTask downTask;

    public static void show(Activity activity, int id, String title){
        Intent intent = new Intent(activity, PdfViewActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt("index", id);
        bundle.putString("title", title);
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    @Override
    protected void getExtras(Bundle extras) {
        this.index = extras.getInt("index");
        this.title = extras.getString("title");
    }

    @Override
    public int initLayout() {
        return R.layout.activity_pdf_view;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        setTitle(title);
    }

    @Override
    public void initData() {
        getData();
    }

    private void checkPdf(){
        boolean isHave = FileUtil.checkFilesExist(Constants.DOWNLOAD_PDF_URL, pdfName+".pdf");
//        LogUtil.e("\n is have: "+isHave+" | folder: "+Constants.DOWNLOAD_PDF_URL+" | fileName: "+pdfName+".pdf");

        if(isHave){
            progressLayout.setVisibility(View.GONE);
            openPdf();
        } else {
            getPdf();
        }
    }

    private void getPdf(){
        GetRequest<File> downRequest = OkGo.get(App.getFileUrl(pdfName));
        downRequest.tag(this);
        downRequest.headers("X-Auth-Token", SPUtils.getInstance(this).getString(SPUtils.TOKEN));

        downTask = OkDownload.request("pdf", downRequest)
                .folder(Constants.DOWNLOAD_PDF_URL)
                .fileName(pdfName+".pdf")
                .save()
                .register(pdfListener);

        downTask.start();
    }

    private void openPdf(){
        String url = Constants.DOWNLOAD_PDF_URL+pdfName+".pdf";
        PDFView.Configurator configurator = pdfView.fromFile(new File(url));

        configurator.spacing(5)
                .enableAntialiasing(true)
                .enableAnnotationRendering(true)
                .onLoad(this)
                .swipeHorizontal(false)
                .enableDoubletap(false)
                .load();
    }

    private void getData() {
        String uri = "api/clz/malist/"+index+"/"+ Constants.PAGE_SIZE+"/"+1;
        OkGo.<BaseBean<ArrayList<MalistBean>>>get(App.getHttpUrl(uri))
                .tag(this)
                .execute(new DialogCallback<ArrayList<MalistBean>>(PdfViewActivity.this) {
                    @Override
                    public void handleSuccess(ArrayList<MalistBean> data) {
                        if(data.size() > 0) {
                            MalistBean bean = data.get(0);
                            pdfName = bean.content;
                            checkPdf();
                        }
                    }

                    @Override
                    public void handleFail(BaseBean body) {
                        super.handleFail(body);
                    }
                });
    }

    @Override
    public void loadComplete(int nbPages) {
        dismissLoading();
    }

    @Override
    public void onPageChanged(int page, int pageCount) {
    }

    @Override
    public void onPageError(int page, Throwable t) {
        t.printStackTrace();
    }

    DownloadListener pdfListener = new DownloadListener(""){
        @Override
        public void onStart(Progress progress) {
            LogUtil.e("onStart: fileFolder: "+progress.folder+" | filePath: "+progress.filePath+" | fileName: "+progress.fileName+" | url: "+progress.url);
        }

        @Override
        public void onProgress(Progress progress) {
            progressBar.setProgress((int)(progress.fraction * 100));
            progressTV.setText("正在下载"+(int)(progress.fraction * 100)+"%");
        }

        @Override
        public void onError(Progress progress) {
            progressTV.setText("下载失败");
            progressBar.setVisibility(View.GONE);
            LogUtil.e("download Error: "+progress.exception.getMessage());
        }

        @Override
        public void onFinish(File file, Progress progress) {
            cancelTask();
            checkPdf();
        }

        @Override
        public void onRemove(Progress progress) {
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cancelTask();
    }

    private void cancelTask(){
        if(null != downTask) {
            downTask.unRegister(pdfListener);
            downTask.remove(false);
        }
    }
}
